﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.DBUtility;
using System.Data.OracleClient;
using Xiaov.SmartWeb.Application.Models;

namespace Xiaov.SmartWeb.Application.SZBBTree
{
  public partial class InitTable : System.Web.UI.Page
  {
    int colIndex = 0;
    private string tableName = "", dwbm = "", nf = "", yf = "";
    XMLVERSION modelXml = null;
    string[] coorList, captionList, editCol, hiddenCol, columnList;//
    Dictionary<string, ENCO_BBZD> dicBBZD = new Dictionary<string, ENCO_BBZD>();
    Dictionary<string, int> dicSJJD = new Dictionary<string, int>();

    protected void Page_Load(object sender, EventArgs e)
    {
      if (Request.QueryString["tableName"] != null || Request.QueryString["dwbm"] != null ||
        Request.QueryString["nf"] != null || Request.QueryString["yf"] != null)
      {
        tableName = Request.QueryString["tableName"].ToString();
        dwbm = Request.QueryString["dwbm"].ToString();
        nf = Request.QueryString["nf"].ToString();
        yf = Request.QueryString["yf"].ToString();
        //InitVersion();
        modelXml = new XMLVERSION(nf, yf, dwbm, tableName);
        string xml = GetXML();
        Response.Write(xml);
      }
      else
      {
        Response.Write("");

      }
      //Response.ContentType = "text/xml";
      ////关键3：告诉浏览器，这是数据，就不要缓存我了
      //Response.CacheControl = "no-cache";
      //Response.Write(s);
      ////关键4：立即关闭Response，后继的html内容统统不要了
      //Response.End();
    }

    private string GetXML()
    {
      string s = @"<?xml version=""1.0"" encoding=""utf-8""?>
<TreeList>
	<Properties Title=""" + modelXml.Title + @""" key=""ZBBM"" HeaderFontIndex=""2"" editAble=true isHiLightModified=true curSelMode=excel
deleteRowAble=false addRowAble=false headerHeight=40 rowHeight=23 sortAble=""false"" curSelBackColor=""#20000000""></Properties>
	<Fonts>
		<Font faceName=""宋体"" Size=""-14""/>
		<Font/>
		<Font faceName=""宋体"" Size=""-14""/>
		<Font bold=""true"" />
	</Fonts>
	<Cols>" + GetCols() + @"
	</Cols>
</TreeList>";
      return s;
    }

    private string GetCols()
    {
      coorList = modelXml.COORDINATES.Split(new char[] { '|' });
      captionList = modelXml.CAPTION.Split(new char[] { ',' });
      hiddenCol = modelXml.HIDDENCOLUMN.Split(new char[] { ',' });
      editCol = modelXml.NotAllowEditColumn.Split(new char[] { ',' });
      columnList = modelXml.SELECTFIELD.Split(new char[] { ',' });
      dicBBZD = GetBBZD();
      dicSJJD = GetSJJD();

      StringBuilder xml = new StringBuilder();
      for (int i = 0; i < coorList.Length; i++)
      {
        string caption = captionList[i];
        string[] parent = coorList[i].Split(new char[] { ',' });
        int px = int.Parse(parent[0].ToString());
        int pxSpan = int.Parse(parent[1].ToString());
        int py = int.Parse(parent[2].ToString());
        int pySpan = int.Parse(parent[3].ToString());
        if (py != 0) //当不为第一行时
        { continue; }
        if (pxSpan > 1 || (pySpan + py) < modelXml.ROWCOUNT) //横向有子节点 或只有一个子节点
        {
          xml.Append("<Group title=\"" + caption + "\">");
          xml.Append(GetChildCol(parent));
          xml.Append("</Group>");
        }
        else//没有子节点
        {
          string zd = columnList[colIndex++].Trim();
          xml.Append(@"<Col name=""" + zd + @""" ");
          if (hiddenCol.Contains(zd))
          {
            xml.Append(" isHide=\"true\" ");
          }
          //if (caption.ToUpper() == "ROWID")
          //{ }
          else
          {
            if (editCol.Contains(zd))
            {
              xml.Append(" editAble=\"false\" ");
            }
            Models.ENCO_BBZD bbzd = dicBBZD[zd];
            if (bbzd.SJLX == "字符型")
            { xml.Append(" dataType=\"string\" "); }
            else
            {
              int jd = 4;
              if (dicSJJD.ContainsKey(zd))
              { jd = dicSJJD[zd]; }
              xml.Append(" isThousandSeparat='false' dataType=\"double\" decimal=\"" + jd.ToString() + "\"");
            }
          }
          if (caption == "指标名称")
          { xml.Append("  width=\"260\" "); }
          else
          { xml.Append("  width=\"fitHeader\" "); }
          string captionRN = caption.Length > 6 ? caption.Substring(0, 5) + "\r\n" + caption.Substring(5, caption.Length - 5) : caption;
          xml.Append(">" + captionRN + "</Col>");
        }
      }
      return xml.ToString();
    }

    public string GetChildCol(string[] parent)
    {
      int px = int.Parse(parent[0].ToString());
      int pxSpan = int.Parse(parent[1].ToString());
      int py = int.Parse(parent[2].ToString());
      int pySpan = int.Parse(parent[3].ToString());

      StringBuilder xml = new StringBuilder();
      for (int i = 0; i < coorList.Length; i++)
      {
        string caption = captionList[i];
        string[] coor = coorList[i].Split(new char[] { ',' });
        int x = int.Parse(coor[0].ToString());
        int xSpan = int.Parse(coor[1].ToString());
        int y = int.Parse(coor[2].ToString());
        int ySpan = int.Parse(coor[3].ToString());
        if (x >= px && x < (px + pxSpan) && y == (py + pySpan))
        {
          if (xSpan > 1 || (ySpan + y) < modelXml.ROWCOUNT)//横向有子节点  或是下方只有一个子节点
          {
            xml.Append("<Group title=\"" + caption + "\">");
            xml.Append(GetChildCol(coor));
            xml.Append("</Group>");
          }
          else//没有子节点
          {
            string zd = columnList[colIndex++].Trim();
            xml.Append(@"<Col name=""" + zd + @""" ");
            if (hiddenCol.Contains(zd))
            { xml.Append(" isHide=\"true\" "); }
            //if (caption.ToUpper() == "ROWID")
            //{ }
            else
            {
              if (editCol.Contains(zd))
              {
                xml.Append(" editAble=\"false\" ");
              }
              Models.ENCO_BBZD bbzd = dicBBZD[zd];
              if (bbzd.SJLX == "字符型")
              { xml.Append(" dataType=\"string\" "); }
              else
              {
                int jd = 4;
                if (dicSJJD.ContainsKey(zd))
                { jd = dicSJJD[zd]; } xml.Append("isThousandSeparat='false' dataType=\"double\"  decimal=\"" + jd.ToString() + "\"");
              }
            }
            if (caption == "指标名称")
            { xml.Append("  width=\"260\" "); }
            else
            { xml.Append("  width=\"fitHeader\" "); }
            string captionRN = caption.Length > 6 ? caption.Substring(0, 5) + "\r\n" + caption.Substring(5, caption.Length - 5) : caption;
            xml.Append(">" + captionRN + "</Col>");
          }
        }
      }

      return xml.ToString();
    }

    private Dictionary<string, ENCO_BBZD> GetBBZD()
    {
      StringBuilder strSql = new StringBuilder();
      strSql.Append("select BBBM,ZD,ZDZS,SJLX,SJCD,SJJD,ZDSX,FLYC ");
      strSql.Append(" FROM ENCO_BBZD ");
      strSql.Append(" where bbbm='" + tableName + "'");
      DataTable dt = DbHelperOra.Query(strSql.ToString()).Tables[0];
      Dictionary<string, ENCO_BBZD> dicBBZD = new Dictionary<string, ENCO_BBZD>();
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        ENCO_BBZD model = new ENCO_BBZD();
        model.BBBM = tableName;
        model.ZD = dt.Rows[i]["zd"].ToString();
        model.SJLX = dt.Rows[i]["sjlx"].ToString();
        model.SJJD = int.Parse(dt.Rows[i]["sjjd"].ToString());
        dicBBZD.Add(model.ZD, model);
      }
      return dicBBZD;
    }

    //获取列对应最大值数据精度
    private Dictionary<string, int> GetSJJD()
    {
      StringBuilder strSql = new StringBuilder();
      strSql.Append("select zd,max(t.sjjd) sjjd from Enco_Sjjdjjbl t ");
      strSql.Append(" where bbbm='" + tableName + "' group by t.zd ");
      DataTable dt = DbHelperOra.Query(strSql.ToString()).Tables[0];
      Dictionary<string, int> dicBBZD = new Dictionary<string, int>();
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        dicBBZD.Add(dt.Rows[i]["zd"].ToString(), int.Parse(dt.Rows[i]["sjjd"].ToString()));
      }
      return dicBBZD;
    }
  }
}